/**
 * Created by HTWX on 2018/3/13.
 */
var express = require('express');
var router = express.Router();
var BaseModel = require('../models/base_model');
var baseModel = new BaseModel();
var CheckLogin = require('../models/checkLogin');
var checkLogin =new CheckLogin();
var Q=require('q');

function bool_addinfo(req,num){
    var deferred = Q.defer();
    var sql = "select yk_report.admincard from yk_report,yk_user where yk_user.user_id=yk_report.user_id and yk_report.paper_id="+ num +" and yk_user.tel="+req.cookies.ownuser+"";
    baseModel.findOneById(sql,function(ret){
        deferred.resolve(ret);
    });
    return deferred.promise;
}

function get_user(req){
    var deferred = Q.defer();
    var sql = "select user_id from yk_user where tel='" + req.cookies.ownuser + "'";
    baseModel.findOneById(sql,function(ret){
            deferred.resolve(ret);
    });
    return deferred.promise;
}

function leftPad(str, c, len) {
    return (Array(len + 1).join(c) + str).substring(str.length);
}

function maxreportid(){
    var deferred = Q.defer();
    var sql = "select report_id from yk_report order by report_id desc limit 0,1";
    baseModel.findOneById(sql,function(ret){
        if(ret) {
            var charstr=ret.report_id+1;
            deferred.resolve('0301120'+leftPad(charstr,'0',9-charstr.toString().length));
        }else{
            deferred.resolve('0301120000000001');
        }
    });
    return deferred.promise;
}

function add_admincard(maxreportid,user_id,paper_id)
{
    var deferred = Q.defer();
    var tableName = 'yk_report';
    var rowInfo = {
        'user_id':user_id,
        'paper_id':paper_id,
        'admincard':maxreportid
    };
    baseModel.insert(tableName,rowInfo,function(ret){
        deferred.resolve(ret);
    });
    return deferred.promise;
}


router.get('/',checkLogin.check);
router.get('/',function(req, res) {
    bool_addinfo(req,req.query.id).then(function(result){
        if(result){
            res.redirect('/init?id='+result.admincard);
        }else{
            Q.all([get_user(req),maxreportid()]).spread(function(rs1,rs2){
                if(rs1&&rs2){
                    add_admincard(rs2,rs1.user_id,req.query.id).then(function(ret){
                        res.redirect('/init?id='+rs2);
                    });
                }
            });
        }
    });
});

module.exports = router;
